﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Security.Cryptography;
using System.Text;

namespace Kis2012.Models
{
    public class CustomMembershipProvider : MembershipProvider
    {
        private string _AppName;
        public override string ApplicationName
        {
            get
            {
                return _AppName;
            }
            set
            {
                _AppName = value;
            }
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            UsersTable userRep = new UsersTable();
            return userRep.UpdateUser(username, oldPassword, newPassword);
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotImplementedException();
        }

        public MembershipUser CreateUser(RegisterModel model, out MembershipCreateStatus status)
        {
            ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(model.UserName, model.Password, true);
            OnValidatingPassword(args);

            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            if (RequiresUniqueEmail && GetUserNameByEmail(model.Email) != string.Empty)
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }

            MembershipUser user = GetUser(model.UserName, true);

            if (user == null)
            {
                /*User newuser = new User();
                newuser.LoginName = model.UserName;
                newuser.LoginPass = GetMD5Hash(model.Password);
                newuser.UserName = model.UserName;
                newuser.UserFullName = model.FullName;
                newuser.UserEmailAddress = model.Email;
                newuser.UserUnit = model.UnitName;
                newuser.IsActive = 1;
                newuser.IsAdmin = 0;
                */
                UsersTable userRep = new UsersTable();
                userRep.RegisterUser(model);

                status = MembershipCreateStatus.Success;

                return GetUser(model.UserName, true);
            }
            else
            {
                status = MembershipCreateStatus.DuplicateUserName;
            }
            return null;
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true);
            OnValidatingPassword(args);

            if (args.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            if (RequiresUniqueEmail && GetUserNameByEmail(email) != string.Empty)
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }

            MembershipUser user = GetUser(username, true);

            if (user == null)
            {
                User newuser = new User();
                newuser.LoginName = username;
                newuser.LoginPass = GetMD5Hash(password);
                newuser.UserName = "Testing";
                newuser.UserFullName = "Tesing 2";
                newuser.UserEmailAddress = email;

                UsersTable userRep = new UsersTable();
                //userRep.RegisterUser(newuser);

                status = MembershipCreateStatus.Success;

                return GetUser(username, true);
            }
            else
            {
                status = MembershipCreateStatus.DuplicateUserName;
            }
            return null;
        }

        private string GetMD5Hash(string password)
        {
            MD5 md5 = MD5.Create();
            byte[] data = md5.ComputeHash(Encoding.Default.GetBytes(password));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotImplementedException();
        }

        public override bool EnablePasswordReset
        {
            get { throw new NotImplementedException(); }
        }

        public override bool EnablePasswordRetrieval
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
              //throw new NotImplementedException();
              //GetAllUsersResult result = db.GetAllUsers().FirstOrDefault();
              
              //userRep.GetAllUsers();

              MembershipUserCollection users = new MembershipUserCollection();
              UsersTable userRep = new UsersTable(); 

              totalRecords = 0;
  
              try 
              {
  
                  int counter = 0;
                  int startIndex = pageSize * pageIndex;
                  int endIndex = startIndex + pageSize - 1;
  
                  foreach(var user in userRep.GetAllUsers()) 
                  {
                      if ((counter >= startIndex) && (counter <= endIndex))
                      {
                          users.Add(new MembershipUser(this.Name,
                          user.LoginName,
                          user.UserId,
                          user.UserEmailAddress,
                          "",
                          null,
                          true,
                          false,
                          DateTime.Now,
                          DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now));
                      }
                      counter++;
                      totalRecords++;
                  }
              }
              catch (Exception e)
              {
                  HttpContext.Current.Response.Write(e.Message);
              }
              
              return users;
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            UsersTable userRep = new UsersTable();
            User user = userRep.GetAllUsers().SingleOrDefault(u => u.LoginName == username);
            if (user != null)
            {
                MemberUser memUser = new MemberUser("CustomMembershipProvider",
                                           username, user.UserId, user.UserEmailAddress,
                                           string.Empty, string.Empty,
                                           true, false, DateTime.MinValue,
                                           DateTime.MinValue,
                                           DateTime.MinValue,
                                           DateTime.Now, DateTime.Now,user.IsAdmin,user.IsActive,user.UserDept,user.UserFullName);
                return memUser;
            }
            return null;
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override string GetUserNameByEmail(string email)
        {
            throw new NotImplementedException();
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { return 3; }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredPasswordLength
        {
            get { return 6; }
        }

        public override int PasswordAttemptWindow
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { throw new NotImplementedException(); }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresUniqueEmail
        {
            get { return false; }
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException();
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotImplementedException();
        }

        public override bool ValidateUser(string username, string password)
        {
            string shalPass = GetMD5Hash(password);
            UsersTable user = new UsersTable();
            User userObj = user.GetUserByName(username, shalPass);
            if (userObj != null)
            {
                return true;
            }
            return false;
        }
    }
}